package com.api.syh56.shengyunhui.util;

import com.api.syh56.shengyunhui.exception.BaseException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;

public class ImageValidator {

    // 检查Base64编码的图片是否符合要求
    public static boolean isValidImage(String base64String) {
        try {
            // 解码Base64字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64String.split(",")[1]);

            // 检查文件大小是否小于2MB
            if (imageBytes.length > 2 * 1024 * 1024) {
                return false;
            }

            // 使用ImageIO读取图片信息
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
            BufferedImage image = ImageIO.read(inputStream);

            // 检查图片边长
            int width = image.getWidth();
            int height = image.getHeight();
            if (width < 15 || height < 15 || width > 8192 || height > 8192) {
                return false;
            }

            // 检查图片格式
            String format = ImageIO.getImageReadersByFormatName("JPEG").next().getFormatName();
            if (!supportedFormats.contains(format)) {
                return false;
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 检查字符串是否是Base64编码
    public static boolean isBase64(String s) {
        return s.matches("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$");
    }

    // 支持的图片格式集合
    private static final Set<String> supportedFormats = new HashSet<String>() {{
        add("JPEG");
        add("JPG");
        add("PNG");
        add("BMP");
        add("TIFF");
    }};



    public static String getBase64FromImageUrl(String imageUrl) {
        try {
            // 创建URL对象
            URL url = new URL(imageUrl);
            System.out.println(url);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 读取响应
            InputStream inputStream = connection.getInputStream();
            byte[] imageBytes = readAllBytes(inputStream);

            // 检查文件大小是否小于2MB
            if (imageBytes.length > 2 * 1024 * 1024) {
                throw new BaseException("请上传2MB以内的图片");
//                return null;
            }

            // 使用ImageIO读取图片信息
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageBytes);
            BufferedImage image = ImageIO.read(byteArrayInputStream);

            // 检查图片边长
            int width = image.getWidth();
            int height = image.getHeight();
            if (width < 15 || height < 15 || width > 8192 || height > 8192) {
                throw new BaseException("请上传15x15px~8192x8192px以内的图片");
//                return null;
            }

            // 检查图片格式
            String format = ImageIO.getImageReadersByFormatName("JPEG").next().getFormatName();
            if (!supportedFormats.contains(format)) {
                throw new BaseException("请上传JPEG、JPG、PNG、BMP、TIFF格式的图片");
//                return null;
            }

            // 转换为Base64
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
//            return null;
        }
    }

    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        // 读取所有字节并返回
        try (ByteArrayInputStream bis = new ByteArrayInputStream(inputStream.readAllBytes())) {
            return bis.readAllBytes();
        }
    }
}